<?php
namespace app\index\controller;

use app\index\model\AccdayListModel;
use app\index\model\AccdayModel;
use app\index\model\AccdayPiaoModel;
use app\index\model\AccdayTwoModel;
use app\index\model\AccountListModel;
use app\index\model\AccountModel;
use app\index\model\BidModel;
use app\index\model\CompanyModel;
use app\index\model\DeptModel;
use app\index\model\EnginModel;
use app\index\model\HouChujinGuanModel;
use app\index\model\HouDayzhiGuanModel;
use app\index\model\HouGonghuiListModel;
use app\index\model\HouGongzhiGuanModel;
use app\index\model\HouGongzhiListModel;
use app\index\model\OptionModel;
use app\index\model\PiaoChuListModel;
use app\index\model\PiaoKaiListModel;
use app\index\model\PiaoShouListModel;
use app\index\model\QianPiaoListModel;
use app\index\model\QianZhiGuanModel;
use app\index\model\TodoModel;
use app\index\model\UserModel;
use app\index\model\WarnModel;
use app\index\model\WorkerModel;
use app\index\service\WarnService;
use app\index\service\WxworkService;
use think\Db;
use think\facade\Config;
use think\Request;

class Task extends Access
{

    public function __construct(Request $request)
    {
        parent::__construct();
        $key = $request->param('key');
        $config_key = Config::get('service.task_key');
        if($key != $config_key){
            exit('server error');
        }
    }


    public function warn(){
        $com = CompanyModel::field('id')->where(['deleted_user'=>0])->select();
        if(count($com) < 1){
            return true;
        }
        foreach ($com as $item){
            $this->com_task($item['id']);
        }
        exit('success');
    }
    public function com_task($comid){
        $data = WarnModel::where(['comid'=>$comid,'state'=>1])->select()->toArray();
        $Obj = new WarnService();
        foreach ($data as $item){
            call_user_func(array($Obj, $item['modname']), $item);
        }
        exit('success');
    }






    /**
     * 预警规则：
     * 以G36“工程累计支付销售方（元）”为分母：
     * 判断1—材料费超比例：款项类型=材料费的，除以G36X100
     * 判断2—劳务人工费超比例：款项类型=劳务人工费的，除以G36X100
     * 判断3—机械租赁费超比例：款项类型=机械租赁费的，除以G36X100
     * 判断4—专业分包费超比例：款项类型=专业分包费的，除以G36X100
     * 判断5—其他费超比例：（G36减去1.2.3.4）除以G36X100
     * 当5个中任意一个或几个超出设置的比例，向指定用户发送站内消息（有几个类型显示几个类型）：
     * [工程名称]成本预警：[材料费]、[劳务人工费]、[机械租赁费]、[专业分包费]、[其他费]超出比例，请关注！
     * */
    public function engin_yu(){
        $com = CompanyModel::field('id')->where(['deleted_user'=>0])->select()->toArray();
        if(count($com) < 1){
            return true;
        }
        foreach ($com as $item){
            $this->engin_yu_task($item['id']);
        }
        exit('success');
    }
    public function engin_yu_task($comid){
        $data = EnginModel::where(['comid'=>$comid,'deleted_user'=>0,'isturn'=>1,'status'=>1,'is_yu'=>'是'])->select()->toArray();
        foreach ($data as $item){
            $item['gongzhimoneygogong'] = HouGongzhiListModel::alias('list')
                ->join('hou_gongzhi zhi','zhi.id=list.gongzhiid')
                ->join('dealcom deal','deal.name=list.fuer')
                ->where(['zhi.comid'=>$comid,'zhi.deleted_user'=>0,'zhi.isturn'=>1,'zhi.status'=>1])
                ->where(['zhi.enginid'=>$item['id'],'deal.type'=>3])
                ->sum('list.money');

            $item['fei_cai'] = HouGongzhiListModel::alias('list')
                ->join('hou_gongzhi zhi','zhi.id=list.gongzhiid')
                ->join('dealcom deal','deal.name=list.fuer')
                ->where(['zhi.comid'=>$comid,'zhi.deleted_user'=>0,'zhi.isturn'=>1,'zhi.status'=>1])
                ->where(['zhi.enginid'=>$item['id'],'deal.type'=>3,'list.zhikuanlei'=>1])
                ->sum('list.money');
            $item['fei_lao'] = HouGongzhiListModel::alias('list')
                ->join('hou_gongzhi zhi','zhi.id=list.gongzhiid')
                ->join('dealcom deal','deal.name=list.fuer')
                ->where(['zhi.comid'=>$comid,'zhi.deleted_user'=>0,'zhi.isturn'=>1,'zhi.status'=>1])
                ->where(['zhi.enginid'=>$item['id'],'deal.type'=>3,'list.zhikuanlei'=>2])
                ->sum('list.money');
            $item['fei_zu'] = HouGongzhiListModel::alias('list')
                ->join('hou_gongzhi zhi','zhi.id=list.gongzhiid')
                ->join('dealcom deal','deal.name=list.fuer')
                ->where(['zhi.comid'=>$comid,'zhi.deleted_user'=>0,'zhi.isturn'=>1,'zhi.status'=>1])
                ->where(['zhi.enginid'=>$item['id'],'deal.type'=>3,'list.zhikuanlei'=>3])
                ->sum('list.money');
            $item['fei_fen'] = HouGongzhiListModel::alias('list')
                ->join('hou_gongzhi zhi','zhi.id=list.gongzhiid')
                ->join('dealcom deal','deal.name=list.fuer')
                ->where(['zhi.comid'=>$comid,'zhi.deleted_user'=>0,'zhi.isturn'=>1,'zhi.status'=>1])
                ->where(['zhi.enginid'=>$item['id'],'deal.type'=>3,'list.zhikuanlei'=>4])
                ->sum('list.money');
            $item['fei_qi'] = round($item['gongzhimoneygogong'] - $item['fei_cai'] - $item['fei_lao'] - $item['fei_zu'] - $item['fei_fen'], 2);

            $item['shi_cai'] = 0;
            $item['shi_lao'] = 0;
            $item['shi_zu'] = 0;
            $item['shi_fen'] = 0;
            $item['shi_qi'] = 0;
            if($item['gongzhimoneygogong'] > 0){
                $item['shi_cai'] = round($item['fei_cai']/$item['gongzhimoneygogong']*100, 2);
                $item['shi_lao'] = round($item['fei_lao']/$item['gongzhimoneygogong']*100, 2);
                $item['shi_zu'] = round($item['fei_zu']/$item['gongzhimoneygogong']*100, 2);
                $item['shi_fen'] = round($item['fei_fen']/$item['gongzhimoneygogong']*100, 2);
                $item['shi_qi'] = round($item['fei_qi']/$item['gongzhimoneygogong']*100, 2);
            }

            $chaoArr = [];
            if($item['shi_cai'] > $item['yu_cai']){
                $chaoArr[] = '[材料费]';
            }
            if($item['shi_lao'] > $item['yu_lao']){
                $chaoArr[] = '[劳务人工费]';
            }
            if($item['shi_zu'] > $item['yu_zu']){
                $chaoArr[] = '[机械租赁费]';
            }
            if($item['shi_fen'] > $item['yu_fen']){
                $chaoArr[] = '[专业分包费]';
            }
            if($item['shi_qi'] > $item['yu_qi']){
                $chaoArr[] = '[其他费]';
            }


            //[工程名称]成本预警：[材料费]、[劳务人工费]、[机械租赁费]、[专业分包费]、[其他费]超出比例，请关注！
            if(count($chaoArr) > 0){
                $mess = '['.$item['name'].']成本预警：';
                foreach ($chaoArr as $keyvv=>$chaoVV){
                    if($keyvv+1 == count($chaoArr)){
                        $mess .= $chaoVV;
                    }else{
                        $mess .= $chaoVV.'、';
                    }
                }
                $mess .= '超出比例，请关注！';
                $this->engin_yu_add_todo($item['yuer'], $mess, $item['id'],'engin');
            }
        }

    }
    public function engin_yu_add_todo($uids, $mess, $mid, $table, $meter=''){
        $name = '工程成本预警';

        if(empty($uids)){
            return true;
        }
        foreach (array_unique(explode(',', $uids)) as $uid){
            $user = UserModel::get_info_by_pk($uid);
            if(!$user || $user['deleted_user'] > 0 || $user['status'] == 0){
                continue;
            }
            TodoModel::insert([
                'table' => $table,
                'meter' => $meter,
                'name' => $name,
                'mess' => $mess,
                'mid' => $mid,
                'uid' => $uid,
                'tododt' => date("Y-m-d H:i:s"),
            ]);
            WorkerModel::insert([
                'type' => 'todo',
                'uid' => $uid,
                'title' => '消息提醒',
                'mess' => $mess,
                'mid' => $mid,
                'table' => $table,
                'meter' => $meter,
                'dt' => date("Y-m-d H:i:s"),
            ]);

            if($user['status'] > 0 && !empty($user['wxuserid'])){
                $res = (new WxworkService())->send_text($user['wxuserid'], 'pagesShow/'.$table.'/show?id='.$mid, '消息提醒', $mess, date("Y-m-d H:i:s"));
            }
        }
        return true;
    }








    public function creaccday(){
        $com = CompanyModel::field('id')->where(['deleted_user'=>0])->select();
        if(count($com) < 1){
            return true;
        }
        foreach ($com as $item){
            $this->com_accday($item['id']);
        }
        exit('success');
    }
    public function com_accday($comid){
        $exist = AccdayModel::where(['comid'=>$comid,'deleted_user'=>0,'dt'=>date("Y-m-d")])->find();
        if($exist){
            return true;
        }


        $accmoney = 0;
        $accIdArr = [];
        $accNameArr = [];
        $accday_two = [];
        $accInfo = AccountModel::where(['comid'=>$comid,'deleted_user'=>0])->select()->toArray();
        foreach ($accInfo as $v){
            $accmoney += $v['accmoney'];
            $accIdArr[] = $v['id'];
            $accNameArr[$v['id']] = $v['name'].'('.$v['accnum'].')';
            $accday_two[$v['id']] = [
                'accname' => $v['name'].'('.$v['accnum'].')',
                'chanidname' => DeptModel::get_name_by_pk($v['chanid']),
                'kainame' => $v['accname'],
                'acctypename' => $this->get_base_showname($comid, 'cai_account_acctype', $v['acctype']),
                'enginname' => EnginModel::where(['id'=>$v['enginid']])->value('name'),
                'dt' => date("Y-m-d"),
                'shangmoney' => 0,
                'shoufee' => 0,
                'zhifee' => 0,
                'money' => 0,
                'accmoney' => $v['accmoney'],
                'created_at' => date('Y-m-d H:i:s'),
            ];
        }


        $shang_shou = AccountListModel::where(['comid'=>$comid])->where('accid','in',$accIdArr)->where('modtype','<',10)
            ->where('created_at','<',date("Y-m-d 00:00:00"))->sum('money');
        $shang_zhi = AccountListModel::where(['comid'=>$comid])->where('accid','in',$accIdArr)->where('modtype','>',10)
            ->where('created_at','<',date("Y-m-d 00:00:00"))->sum('money');
        //上日余额
        $shangmoney = round($accmoney + $shang_shou - $shang_zhi, 2);


        //今日交易信息
        $todayinfo = AccountListModel::alias('list')
            ->field('list.kuanid,list.money,list.accid,list.dt,list.modtype,list.explain,kuan.billid
                ,kuan.bidid,kuan.enginid,kuan.zhai,kuan.kuanlei,kuan.duier,kuan.mid,kuan.listid')
            ->join('acckuan kuan','kuan.id=list.kuanid')
            ->where(['list.comid'=>$comid])
            ->where('list.accid','in',$accIdArr)
            ->where('list.created_at','>=',date("Y-m-d 00:00:00"))
            ->select()->toArray();

        $today_shou = 0;
        $today_zhi = 0;
        $accday_list = [];
        foreach ($todayinfo as $vv){
            if($vv['modtype'] < 10){
                $accday_two[$vv['accid']]['shoufee'] += $vv['money'];
                $today_shou += $vv['money'];
            }else{
                $accday_two[$vv['accid']]['zhifee'] += $vv['money'];
                $today_zhi += $vv['money'];
            }


            $enginname = '';
            $gui_unit = '';
            if($vv['bidid'] > 0){
                $enginInfo = BidModel::where(['id'=>$vv['bidid']])->find();
                $enginname = $enginInfo['name'];
                $gui_unit = DeptModel::get_name_by_pk($enginInfo['gui_unit']);
            }
            if($vv['enginid'] > 0){
                $enginInfo = EnginModel::where(['id'=>$vv['enginid']])->find();
                $enginname = $enginInfo['name'];
                $gui_unit = DeptModel::get_name_by_pk($enginInfo['gui_unit']);
            }


            $piaoList = [];
            //工程回款【2】
            if($vv['modtype'] == 2){
                $gonghuilist = HouGonghuiListModel::where(['gonghuiid'=>$vv['mid']])->select()->toArray();
                foreach ($gonghuilist as $gonghuivv){
                    $piaoKaiDt = PiaoKaiListModel::alias('list')
                        ->join('piao_kai zhu','zhu.id=list.kaiid')
                        ->where(['zhu.deleted_user'=>0,'zhu.isturn'=>1,'zhu.status'=>1])
                        ->where(['list.id'=>$gonghuivv['piaoid']])
                        ->value('zhu.dt');
                    if(!$piaoKaiDt || $piaoKaiDt == '0000-00-00'){
                        $piaoKaiDt = '';
                    }
                    $piaoList[] = ['dt'=>$piaoKaiDt, 'money'=>$gonghuivv['xiaofee']];
                }
            }
            //工程付款【11】
            if($vv['modtype'] == 11){
                $gongzhiguan = HouGongzhiGuanModel::alias('guan')
                    ->field('guan.*')
                    ->join('hou_gongzhi zhi','zhi.id=guan.gongzhiid')
                    ->join('piao_shou piao','piao.id=guan.piaoid')
                    ->where(['zhi.comid'=>$comid,'zhi.deleted_user'=>0,'zhi.isturn'=>1,'zhi.status'=>1])
                    ->where(['piao.comid'=>$comid,'piao.deleted_user'=>0,'piao.isturn'=>1,'piao.status'=>1])
                    ->where(['guan.gongzhiid'=>$vv['mid'],'guan.gongzhilistid'=>$vv['listid']])
                    ->select()->toArray();
                foreach ($gongzhiguan as $gongzhiguanvv){
                    $piaoKaiDt = PiaoShouListModel::alias('list')
                        ->join('piao_shou zhu','zhu.id=list.shouid')
                        ->where(['zhu.deleted_user'=>0,'zhu.isturn'=>1,'zhu.status'=>1])
                        ->where(['list.id'=>$gongzhiguanvv['piaolistid']])
                        ->value('list.kaidt');
                    if(!$piaoKaiDt || $piaoKaiDt == '0000-00-00'){
                        $piaoKaiDt = '';
                    }
                    $piaoList[] = ['dt'=>$piaoKaiDt, 'money'=>$gongzhiguanvv['difee']];
                }
            }

            //前期费支付【12】
            if($vv['modtype'] == 12){
                $qianzhiguan = QianZhiGuanModel::alias('guan')
                    ->field('guan.*')
                    ->join('qian_zhi zhi','zhi.id=guan.zhiid')
                    ->join('qian_piao piao','piao.id=guan.piaoid')
                    ->where(['zhi.comid'=>$comid,'zhi.deleted_user'=>0,'zhi.isturn'=>1,'zhi.status'=>1])
                    ->where(['piao.comid'=>$comid,'piao.deleted_user'=>0,'piao.isturn'=>1,'piao.status'=>1])
                    ->where(['guan.zhiid'=>$vv['mid'],'guan.zhilistid'=>$vv['listid']])
                    ->select()->toArray();
                foreach ($qianzhiguan as $qianzhiguanvv){
                    $piaoKaiDt = QianPiaoListModel::alias('list')
                        ->join('qian_piao zhu','zhu.id=list.piaoid')
                        ->where(['zhu.deleted_user'=>0,'zhu.isturn'=>1,'zhu.status'=>1])
                        ->where(['list.id'=>$qianzhiguanvv['piaolistid']])
                        ->value('list.kaidt');
                    if(!$piaoKaiDt || $piaoKaiDt == '0000-00-00'){
                        $piaoKaiDt = '';
                    }
                    $piaoList[] = ['dt'=>$piaoKaiDt, 'money'=>$qianzhiguanvv['difee']];
                }
            }
            //储备进项支付【16】
            if($vv['modtype'] == 16){
                $chujinguan = HouChujinGuanModel::alias('guan')
                    ->field('guan.*')
                    ->join('hou_chujin jin','jin.id=guan.chujinid')
                    ->join('piao_chu piao','piao.id=guan.piaoid')
                    ->where(['jin.comid'=>$comid,'jin.deleted_user'=>0,'jin.isturn'=>1,'jin.status'=>1])
                    ->where(['piao.comid'=>$comid,'piao.deleted_user'=>0,'piao.isturn'=>1,'piao.status'=>1])
                    ->where(['guan.chujinid'=>$vv['mid'],'guan.chujinlistid'=>$vv['listid']])
                    ->select()->toArray();
                foreach ($chujinguan as $chujinguanvv){
                    $piaoKaiDt = PiaoChuListModel::alias('list')
                        ->join('piao_chu zhu','zhu.id=list.piaochuid')
                        ->where(['zhu.deleted_user'=>0,'zhu.isturn'=>1,'zhu.status'=>1])
                        ->where(['list.id'=>$chujinguanvv['piaolistid']])
                        ->value('list.kaidt');
                    if(!$piaoKaiDt || $piaoKaiDt == '0000-00-00'){
                        $piaoKaiDt = '';
                    }
                    $piaoList[] = ['dt'=>$piaoKaiDt, 'money'=>$chujinguanvv['difee']];
                }
            }

            //日常付款【19】
            if($vv['modtype'] == 19){
                $dayzhiguan = HouDayzhiGuanModel::alias('guan')
                    ->field('guan.*')
                    ->join('hou_dayzhi zhi','zhi.id=guan.dayzhiid')
                    ->join('piao_day piao','piao.id=guan.piaoid')
                    ->where(['zhi.comid'=>$comid,'zhi.deleted_user'=>0,'zhi.isturn'=>1,'zhi.status'=>1])
                    ->where(['piao.comid'=>$comid,'piao.deleted_user'=>0,'piao.isturn'=>1,'piao.status'=>1])
                    ->where(['guan.dayzhiid'=>$vv['mid'],'guan.dayzhilistid'=>$vv['listid']])
                    ->select()->toArray();
                foreach ($dayzhiguan as $dayzhiguanvv){
                    $piaoKaiDt = PiaoChuListModel::alias('list')
                        ->join('piao_day zhu','zhu.id=list.dayid')
                        ->where(['zhu.deleted_user'=>0,'zhu.isturn'=>1,'zhu.status'=>1])
                        ->where(['list.id'=>$dayzhiguanvv['piaolistid']])
                        ->value('list.kaidt');
                    if(!$piaoKaiDt || $piaoKaiDt == '0000-00-00'){
                        $piaoKaiDt = '';
                    }
                    $piaoList[] = ['dt'=>$piaoKaiDt, 'money'=>$dayzhiguanvv['difee']];
                }
            }



            foreach ($accday_two as $twoKK=>&$twoVV){
                $wang_shou = AccountListModel::where(['comid'=>$comid,'accid'=>$twoKK])->where('modtype','<',10)
                    ->where('created_at','<',date("Y-m-d 00:00:00"))->sum('money');
                $wang_zhi = AccountListModel::where(['comid'=>$comid,'accid'=>$twoKK])->where('modtype','>',10)
                    ->where('created_at','<',date("Y-m-d 00:00:00"))->sum('money');
                $twoVV['shangmoney'] = round($twoVV['accmoney'] + $wang_shou - $wang_zhi, 2);
                $twoVV['money'] = round($twoVV['shangmoney'] + $twoVV['shoufee'] - $twoVV['zhifee'], 2);
            }



            $accday_list[] = [
                'billid' => $vv['billid'],
                'mid' => $vv['mid'],
                'listid' => $vv['listid'],
                'modtype' => $vv['modtype'],
                'accname' => $accNameArr[$vv['accid']],
                'dt' => $vv['dt'],
                'duier' => $vv['duier'],
                'kuanlei' => $vv['kuanlei'],
                'zhai' => $vv['zhai'],
                'enginname' => $enginname,
                'gui_unit' => $gui_unit,
                'money' => $vv['money'],
                'explain' => $vv['explain'],
                'piao' => $piaoList,
            ];
        }

        $today_money = round($shangmoney + $today_shou - $today_zhi, 2);


        $param['comid'] = $comid;
        $param['created_user'] = $param['updated_user'] = 0;
        $param['created_at'] = $param['updated_at']= date('Y-m-d H:i:s');
        $param['deptid'] = 0;
        $param['chanid'] = 0;


        Db::startTrans();
        try {
            $exist = AccdayModel::where(['comid'=>$comid,'deleted_user'=>0,'dt'=>date("Y-m-d")])->find();
            if($exist){
                AccdayModel::where(['id'=>$exist['id']])->update([
                    'comid' => $param['comid'],
                    'created_at' => $param['created_at'],
                    'updated_at' => $param['created_at'],
                    'deptid' => $param['deptid'],
                    'chanid' => $param['chanid'],
                    'dt' => date("Y-m-d"),
                    'shangmoney' => $shangmoney,
                    'shoufee' => $today_shou,
                    'zhifee' => $today_zhi,
                    'money' => $today_money,
                ]);
                $accdayid = $exist['id'];
            }else{
                $accdayid = AccdayModel::insertGetId([
                    'comid' => $param['comid'],
                    'created_at' => $param['created_at'],
                    'updated_at' => $param['created_at'],
                    'deptid' => $param['deptid'],
                    'chanid' => $param['chanid'],
                    'dt' => date("Y-m-d"),
                    'shangmoney' => $shangmoney,
                    'shoufee' => $today_shou,
                    'zhifee' => $today_zhi,
                    'money' => $today_money,
                ]);
            }

            AccdayTwoModel::where(['accdayid'=>$accdayid])->delete();
            foreach ($accday_two as $itemTwo){
                $itemTwo['accdayid'] = $accdayid;
                unset($itemTwo['accmoney']);
                AccdayTwoModel::insert($itemTwo);
            }


            AccdayListModel::where(['accdayid'=>$accdayid])->delete();
            AccdayPiaoModel::where(['accdayid'=>$accdayid])->delete();
            foreach ($accday_list as $item){
                $item['accdayid'] = $accdayid;
                $piaoList = $item['piao'];
                unset($item['piao']);

                $accdaylistid = AccdayListModel::insertGetId($item);
                foreach ($piaoList as $piaoVV){
                    $piaoVV['accdayid'] = $accdayid;
                    $piaoVV['accdaylistid'] = $accdaylistid;
                    AccdayPiaoModel::insertGetId($piaoVV);
                }
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            dump($e->getMessage());die;
        }

        return true;
    }




















    public function get_base_showname($comid, $num = '', $keyid){
        if(empty($num) || empty($keyid)){
            return '';
        }
        $option_id = OptionModel::get_pk_by_num($comid, $num);
        $name = OptionModel::where(['comid'=>$comid,'deleted_user'=>0,'topid'=>$option_id, 'keyid'=>$keyid])->value('name');
        return $name;
    }

}
